<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="概述&amp;nbsp;&amp;nbsp;Hive是建立在Hadoop上的数据仓库基础架构。它提供了一系列的工具，用来进行数据提取、转换、加载，这是一种可以存储、查询和分析存储在Hadoop中的大规模数据机制。可以把Hadoop下结构化数据文件映射为一张成Hive中的表，并提供类sql查询功能，除了不支持更新、索引和事务，sql其它功能都支持。可以将sql语句转换为MapReduce任务进行运行，作为sql到">
<meta property="og:type" content="article">
<meta property="og:title" content="Hadoop学习笔记(5)-Hive">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/18/2016-07-18-Hadoop05-Hive/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="概述&amp;nbsp;&amp;nbsp;Hive是建立在Hadoop上的数据仓库基础架构。它提供了一系列的工具，用来进行数据提取、转换、加载，这是一种可以存储、查询和分析存储在Hadoop中的大规模数据机制。可以把Hadoop下结构化数据文件映射为一张成Hive中的表，并提供类sql查询功能，除了不支持更新、索引和事务，sql其它功能都支持。可以将sql语句转换为MapReduce任务进行运行，作为sql到">
<meta property="og:locale">
<meta property="og:image" content="http://ww2.sinaimg.cn/mw690/63503acbjw1f5x3hcttd1j20ai0513yq.jpg">
<meta property="article:published_time" content="2016-07-18T10:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="Hadoop">
<meta property="article:tag" content="大数据">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ww2.sinaimg.cn/mw690/63503acbjw1f5x3hcttd1j20ai0513yq.jpg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/18/2016-07-18-Hadoop05-Hive/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>Hadoop学习笔记(5)-Hive | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%83%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8"><span class="nav-number">2.</span> <span class="nav-text">元数据存储</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8"><span class="nav-number">3.</span> <span class="nav-text">数据存储</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hive%E5%B8%B8%E7%94%A8%E4%BC%98%E5%8C%96%E6%96%B9%E6%B3%95"><span class="nav-number">4.</span> <span class="nav-text">Hive常用优化方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85Hive"><span class="nav-number">5.</span> <span class="nav-text">安装Hive</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hive-QL"><span class="nav-number">6.</span> <span class="nav-text">Hive QL</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E6%A0%BC%E5%BC%8F"><span class="nav-number">6.1.</span> <span class="nav-text">文件格式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#create-table"><span class="nav-number">6.2.</span> <span class="nav-text">create table</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#insert-select"><span class="nav-number">6.3.</span> <span class="nav-text">insert select</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#load-data"><span class="nav-number">6.4.</span> <span class="nav-text">load data</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#external-table"><span class="nav-number">6.5.</span> <span class="nav-text">external table</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CTAS"><span class="nav-number">6.6.</span> <span class="nav-text">CTAS</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Partition"><span class="nav-number">6.7.</span> <span class="nav-text">Partition</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Array-amp-amp-Map"><span class="nav-number">6.8.</span> <span class="nav-text">Array&amp;&amp;Map</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#UDF"><span class="nav-number">7.</span> <span class="nav-text">UDF</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B7%BB%E5%8A%A0jar%E5%8C%85%E5%88%B0Hive"><span class="nav-number">7.1.</span> <span class="nav-text">添加jar包到Hive</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E4%B8%B4%E6%97%B6%E5%87%BD%E6%95%B0"><span class="nav-number">7.2.</span> <span class="nav-text">创建临时函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E6%B0%B8%E4%B9%85%E5%87%BD%E6%95%B0"><span class="nav-number">7.3.</span> <span class="nav-text">创建永久函数</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/18/2016-07-18-Hadoop05-Hive/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Hadoop学习笔记(5)-Hive
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2016-07-18 18:00:00" itemprop="dateCreated datePublished" datetime="2016-07-18T18:00:00+08:00">2016-07-18</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/%E5%A4%A7%E6%95%B0%E6%8D%AE/" itemprop="url" rel="index"><span itemprop="name">大数据</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/%E5%A4%A7%E6%95%B0%E6%8D%AE/Hadoop/" itemprop="url" rel="index"><span itemprop="name">Hadoop</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p><img src="http://ww2.sinaimg.cn/mw690/63503acbjw1f5x3hcttd1j20ai0513yq.jpg"></p>
<h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>&nbsp;&nbsp;Hive是建立在Hadoop上的数据仓库基础架构。它提供了一系列的工具，用来进行数据提取、转换、加载，这是一种可以存储、查询和分析存储在Hadoop中的大规模数据机制。可以把Hadoop下结构化数据文件映射为一张成Hive中的表，并提供类sql查询功能，除了不支持更新、索引和事务，sql其它功能都支持。可以将sql语句转换为MapReduce任务进行运行，作为sql到MapReduce的映射器。提供shell、JDBC/ODBC、Thrift、Web等接口。</p>
<p>&nbsp;&nbsp;Hive 并不适合那些需要低延迟的应用，例如，联机事务处理（OLTP）。Hive 查询操作过程严格遵守Hadoop MapReduce 的作业执行模型，Hive 将用户的HiveQL 语句通过解释器转换为MapReduce 作业提交到Hadoop 集群上，Hadoop 监控作业执行过程，然后返回作业执行结果给用户。Hive 并非为联机事务处理而设计，Hive 并不提供实时的查询和基于行级的数据更新操作。Hive 的最佳使用场合是大数据集的批处理作业，例如，网络日志分析。</p>
<h3 id="元数据存储"><a href="#元数据存储" class="headerlink" title="元数据存储"></a>元数据存储</h3><p>&nbsp;&nbsp;Hive将元数据存储在RDBMS中，有三种方式可以连接到数据库。</p>
<ol>
<li>内嵌模式：元数据保持在内嵌数据库的Derby，一般用于单元测试，只允许一个会话连接。</li>
<li>多用户模式：在本地安装Mysql，把元数据放到Mysql内。</li>
<li>远程模式：元数据放置在远程的Mysql数据库。</li>
</ol>
<h3 id="数据存储"><a href="#数据存储" class="headerlink" title="数据存储"></a>数据存储</h3><p> &nbsp;&nbsp;Hive没有专门的数据存储格式，也没有为数据建立索引，用于可以非常自由的组织Hive中的表，只需要在创建表的时候告诉Hive数据中的列分隔符和行分隔符。</p>
<p> &nbsp;&nbsp;Hive中所有的数据都存储在HDFS中，Hive中包含4中数据模型：Tabel、ExternalTable、Partition、Bucket。</p>
<p> <strong>Table</strong></p>
<p> &nbsp;&nbsp;类似与传统数据库中的Table，每一个Table在Hive中都有一个相应的目录来存储数据。例如：一个表zz，它在HDFS中的路径为：/wh/zz，其中wh是在hive-site.xml中由${hive.metastore.warehouse.dir}指定的数据仓库的目录，所有的Table数据（不含External Table）都保存在这个目录中。</p>
<p> <strong>Partition</strong></p>
<p> &nbsp;&nbsp;类似于传统数据库中划分列的索引。在Hive中，表中的一个Partition对应于表下的一个目录，所有的Partition数据都存储在对应的目录中。例如：zz表中包含ds和city两个Partition，则对应于ds=20140214，city=beijing的HDFS子目录为：/wh/zz/ds=20140214/city=Beijing。</p>
<p> <strong>ExternalTable</strong></p>
<p> &nbsp;&nbsp;指向已存在HDFS中的数据，可创建Partition。和Table在元数据组织结构相同，在实际存储上有较大差异。Table创建和数据加载过程，可以用统一语句实现，实际数据被转移到数据仓库目录中，之后对数据的访问将会直接在数据仓库的目录中完成。删除表时，表中的数据和元数据都会删除。ExternalTable只有一个过程，因为加载数据和创建表是同时完成。时间数据是存储在Location后面指定的HDFS路径中的，并不会移动到数据仓库中。</p>
<p> <strong>Bcuket</strong></p>
<p> &nbsp;&nbsp;对指定列计算的hash，根据hash值切分数据，目的是为了便于并行，每一个Buckets对应一个文件。将user列分数至32个Bucket上，首先对user列的值计算hash，比如，对应hash=0的HDFS目录为：/wh/zz/ds=20140214/city=Beijing/part-00000;对应hash=20的，目录为：/wh/zz/ds=20140214/city=Beijing/part-00020。</p>
<h3 id="Hive常用优化方法"><a href="#Hive常用优化方法" class="headerlink" title="Hive常用优化方法"></a>Hive常用优化方法</h3><ol>
<li>join连接时的优化：当三个或多个以上的表进行join操作时，如果每个on使用相同的字段连接时只会产生一个mapreduce。</li>
<li>join连接时的优化：当多个表进行查询时，从左到右表的大小顺序应该是从小到大。原因：hive在对每行记录操作时会把其他表先缓存起来，直到扫描最后的表进行计算。</li>
<li>在where字句中增加分区过滤器。</li>
<li>当可以使用left semi join 语法时不要使用inner join，前者效率更高。原因：对于左表中指定的一条记录，一旦在右表中找到立即停止扫描。</li>
<li>如果所有表中有一张表足够小，则可置于内存中，这样在和其他表进行连接的时候就能完成匹配，省略掉reduce过程。设置属性即可实现，set hive.auto.covert.join=true; 用户可以配置希望被优化的小表的大小 set hive.mapjoin.smalltable.size=2500000; 如果需要使用这两个配置可置入$HOME/.hiverc文件中。</li>
<li>同一种数据的多种处理：从一个数据源产生的多个数据聚合，无需每次聚合都需要重新扫描一次。<br>例如:insert overwrite table student select *　from employee; insert overwrite table person select * from employee;<br>可以优化成 from employee insert overwrite table student select * insert overwrite table person select *</li>
<li>limit调优：limit语句通常是执行整个语句后返回部分结果。set hive.limit.optimize.enable=true;</li>
<li>开启并发执行。某个job任务中可能包含众多的阶段，其中某些阶段没有依赖关系可以并发执行，开启并发执行后job任务可以更快的完成。设置属性：set hive.exec.parallel=true;</li>
<li>hive提供的严格模式，禁止3种情况下的查询模式。<ul>
<li>当表为分区表时，where字句后没有分区字段和限制时，不允许执行。</li>
<li>当使用order by语句时，必须使用limit字段，因为order by 只会产生一个reduce任务。</li>
<li>限制笛卡尔积的查询。</li>
</ul>
</li>
<li>合理的设置map和reduce数量。</li>
<li>jvm重用。可在hadoop的mapred-site.xml中设置jvm被重用的次数。</li>
</ol>
<h3 id="安装Hive"><a href="#安装Hive" class="headerlink" title="安装Hive"></a>安装Hive</h3><ol>
<li>解压Hive。</li>
<li>将mysql的驱动jar包copy到${HIVE_HOME}/lib目录下。</li>
<li>cp hive-default.xml.template  hive-size.xml。</li>
<li>配置hive-size.xml。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"> &lt;configuration&gt;</span><br><span class="line">	&lt;!-- 指定数据库URL --&gt;</span><br><span class="line">	&lt;property&gt;</span><br><span class="line">		&lt;name&gt;javax.jdo.option.ConnectionURL&lt;&#x2F;name&gt;</span><br><span class="line">		&lt;value&gt;jdbc:mysql:&#x2F;&#x2F;192.168.145.148:3306&#x2F;hive?createDatabaseIfNotExist&#x3D;true&lt;&#x2F;value&gt;</span><br><span class="line">	&lt;&#x2F;property&gt;</span><br><span class="line">	&lt;property&gt;</span><br><span class="line">		&lt;name&gt;javax.jdo.option.ConnectionDriverName&lt;&#x2F;name&gt;</span><br><span class="line">		&lt;value&gt;com.mysql.jdbc.Driver&lt;&#x2F;value&gt;</span><br><span class="line">	&lt;&#x2F;property&gt;</span><br><span class="line">	&lt;property&gt;</span><br><span class="line">		&lt;name&gt;javax.jdo.option.ConnectionUserName&lt;&#x2F;name&gt;</span><br><span class="line">		&lt;value&gt;root&lt;&#x2F;value&gt;</span><br><span class="line">	&lt;&#x2F;property&gt;</span><br><span class="line">	&lt;property&gt;</span><br><span class="line">		&lt;name&gt;javax.jdo.option.ConnectionPassword&lt;&#x2F;name&gt;</span><br><span class="line">		&lt;value&gt;root&lt;&#x2F;value&gt;</span><br><span class="line">	&lt;&#x2F;property&gt;</span><br><span class="line">&lt;&#x2F;configuration&gt;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Hive-QL"><a href="#Hive-QL" class="headerlink" title="Hive QL"></a>Hive QL</h3><h4 id="文件格式"><a href="#文件格式" class="headerlink" title="文件格式"></a>文件格式</h4><p>&nbsp;&nbsp;Hive创建表可以指定四种文件格式。</p>
<ol>
<li>文本格式的数据是Hadoop中经常碰到的。如TextFile 、XML和JSON。 文本格式除了会占用更多磁盘资源外，对它的解析开销一般会比二进制格式高几十倍以上，尤其是XML 和JSON，它们的解析开销比Textfile 还要大，因此强烈不建议在生产系统中使用这些格式进行储存。如果需要输出这些格式，请在客户端做相应的转换操作。 文本格式经常会用于日志收集，数据库导入，Hive默认配置也是使用文本格式，而且常常容易忘了压缩，所以请确保使用了正确的格式。另外文本格式的一个缺点是它不具备类型和模式，比如销售金额、利润这类数值数据或者日期时间类型的数据，如果使用文本格式保存，由于它们本身的字符串类型的长短不一，或者含有负数，导致MR没有办法排序，所以往往需要将它们预处理成含有模式的二进制格式，这又导致了不必要的预处理步骤的开销和储存资源的浪费。</li>
<li>SequenceFile是Hadoop API 提供的一种二进制文件，它将数据以&lt;key,value&gt;的形式序列化到文件中。这种二进制文件内部使用Hadoop 的标准的Writable 接口实现序列化和反序列化。它与Hadoop API中的MapFile 是互相兼容的。Hive 中的SequenceFile 继承自Hadoop API 的SequenceFile，不过它的key为空，使用value 存放实际的值， 这样是为了避免MR 在运行map 阶段的排序过程。如果你用Java API 编写SequenceFile，并让Hive 读取的话，请确保使用value字段存放数据，否则你需要自定义读取这种SequenceFile 的InputFormat class 和OutputFormat class。</li>
<li>RCFile是Hive推出的一种专门面向列的数据格式。 它遵循“先按列划分，再垂直划分”的设计理念。当查询过程中，针对它并不关心的列时，它会在IO上跳过这些列。需要说明的是，RCFile在map阶段从远端拷贝仍然是拷贝整个数据块，并且拷贝到本地目录后RCFile并不是真正直接跳过不需要的列，并跳到需要读取的列， 而是通过扫描每一个row group的头部定义来实现的，但是在整个HDFS Block 级别的头部并没有定义每个列从哪个row group起始到哪个row group结束。所以在读取所有列的情况下，RCFile的性能反而没有SequenceFile高。</li>
<li>Avro是一种用于支持数据密集型的二进制文件格式。它的文件格式更为紧凑，若要读取大量数据时，Avro能够提供更好的序列化和反序列化性能。并且Avro数据文件天生是带Schema定义的，所以它不需要开发者在API 级别实现自己的Writable对象。</li>
<li>其他格式:Hadoop实际上支持任意文件格式，只要能够实现对应的RecordWriter和RecordReader即可。其中数据库格式也是会经常储存在Hadoop中，比如Hbase，Mysql，Cassandra，MongoDB。 这些格式一般是为了避免大量的数据移动和快速装载的需求而用的。他们的序列化和反序列化都是由这些数据库格式的客户端完成，并且文件的储存位置和数据布局(Data Layout)不由Hadoop控制，他们的文件切分也不是按HDFS的块大小（blocksize）进行切割。</li>
</ol>
<h4 id="create-table"><a href="#create-table" class="headerlink" title="create table"></a>create table</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">create table test_user(id int,name string) </span><br><span class="line">    &#x2F;&#x2F; 注释</span><br><span class="line">    comment &#39;This is the test table&#39;</span><br><span class="line">    row format delimited</span><br><span class="line">    &#x2F;&#x2F; 指定切分格式规则</span><br><span class="line">    fields terminated by &#39;,&#39;</span><br><span class="line">    &#x2F;&#x2F; 指定文件格式</span><br><span class="line">    stored as textfile; </span><br></pre></td></tr></table></figure>
<h4 id="insert-select"><a href="#insert-select" class="headerlink" title="insert select"></a>insert select</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;使用select语句来批量插入数据</span><br><span class="line">insert overwrite table test_user select * from tab_user;</span><br></pre></td></tr></table></figure>
<h4 id="load-data"><a href="#load-data" class="headerlink" title="load data"></a>load data</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;从本地导入数据到hive的表中（实质就是将文件上传到hdfs中hive管理目录下）</span><br><span class="line">load data local inpath &#39;&#x2F;home&#x2F;hadoop&#x2F;test.txt&#39; into table test_user;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;从hdfs上导入数据到hive表中（实质就是将文件从原始目录移动到hive管理的目录下）</span><br><span class="line">load data inpath &#39;hdfs:&#x2F;&#x2F;ns1&#x2F;data.log&#39; into table test_user;</span><br></pre></td></tr></table></figure>
<h4 id="external-table"><a href="#external-table" class="headerlink" title="external table"></a>external table</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;LOCATION指定的是hdfs路径</span><br><span class="line">&#x2F;&#x2F;如果LOCATION路径有数据,则可以直接映射数据建表</span><br><span class="line">CREATE EXTERNAL TABLE test_user_external(id int, name string)</span><br><span class="line"> ROW FORMAT DELIMITED</span><br><span class="line"> FIELDS TERMINATED BY &#39;,&#39;</span><br><span class="line"> STORED AS TEXTFILE</span><br><span class="line"> LOCATION &#39;&#x2F;external&#x2F;user&#39;;</span><br></pre></td></tr></table></figure>
<h4 id="CTAS"><a href="#CTAS" class="headerlink" title="CTAS"></a>CTAS</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;CTAS是通过查询,然后根据查询的结果来建立表格的一种方式。</span><br><span class="line">&#x2F;&#x2F;CTAS会根据SELECT语句创建表结构,并把数据一并复制过来。</span><br><span class="line">CREATE TABLE test_user_ctas</span><br><span class="line">   AS</span><br><span class="line">SELECT id new_id, name new_name</span><br><span class="line">FROM test_user</span><br><span class="line">SORT BY new_id;</span><br></pre></td></tr></table></figure>
<h4 id="Partition"><a href="#Partition" class="headerlink" title="Partition"></a>Partition</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;创建一个分区表,以year年份作为分区字段</span><br><span class="line">create table test_user_part(id int,name string) </span><br><span class="line">    partitioned by (year string)</span><br><span class="line">    row format delimited fields terminated by &#39;,&#39;;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;将data.log导入到test_user_part表中,并设置分区为1990    </span><br><span class="line">load data local inpath &#39;&#x2F;home&#x2F;hadoop&#x2F;data.log&#39; overwrite into table test_user_part</span><br><span class="line">     partition(year&#x3D;&#39;1990&#39;);</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">load data local inpath &#39;&#x2F;home&#x2F;hadoop&#x2F;data2.log&#39; overwrite into table test_user_part</span><br><span class="line">     partition(year&#x3D;&#39;2000&#39;);</span><br></pre></td></tr></table></figure>
<h4 id="Array-amp-amp-Map"><a href="#Array-amp-amp-Map" class="headerlink" title="Array&amp;&amp;Map"></a>Array&amp;&amp;Map</h4><p>&nbsp;&nbsp;hive中的列支持使用struct、map和array集合数据类型。大多数关系型数据库中不支持这些集合数据类型，因为它们会破坏标准格式。关系型数据库中为实现集合数据类型是由多个表之间建立合适的外键关联来实现。在大数据系统中，使用集合类型的数据的好处在于提高数据的吞吐量，减少寻址次数来提高查询速度。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;array </span><br><span class="line">create table tab_array(a array&lt;int&gt;,b array&lt;string&gt;)</span><br><span class="line">row format delimited</span><br><span class="line">fields terminated by &#39;\t&#39;</span><br><span class="line">collection items terminated by &#39;,&#39;;</span><br><span class="line"></span><br><span class="line">select a[0] from tab_array;</span><br><span class="line">select * from tab_array where array_contains(b,&#39;word&#39;);</span><br><span class="line">insert into table tab_array select array(0),array(name,ip) from tab_ext t; </span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;map</span><br><span class="line">create table tab_map(name string,info map&lt;string,string&gt;)</span><br><span class="line">row format delimited</span><br><span class="line">fields terminated by &#39;\t&#39;</span><br><span class="line">collection items terminated by &#39;,&#39;</span><br><span class="line">map keys terminated by &#39;:&#39;;</span><br><span class="line"></span><br><span class="line">load data local inpath &#39;&#x2F;home&#x2F;hadoop&#x2F;hivetemp&#x2F;tab_map.txt&#39; overwrite into table tab_map;</span><br><span class="line">insert into table tab_map select name,map(&#39;name&#39;,name,&#39;ip&#39;,ip) from tab_ext; </span><br></pre></td></tr></table></figure>
<h3 id="UDF"><a href="#UDF" class="headerlink" title="UDF"></a>UDF</h3><p>&nbsp;&nbsp;UDF即用户自定义函数(User Defined Function),Hive支持UDF进行自定义函数的编写。</p>
<p>&nbsp;&nbsp;需要先使用Java代码开发UDF,然后再把jar包导入到Hive中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FindRegionByPhone</span> <span class="keyword">extends</span> <span class="title">UDF</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//使用map模拟数据库</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> HashMap&lt;String,String&gt;  dataDictionary = <span class="keyword">new</span> HashMap&lt;String,String&gt;();</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">static</span>&#123;</span><br><span class="line">		dataDictionary.put(<span class="string">&quot;136&quot;</span>,<span class="string">&quot;beijing&quot;</span>);</span><br><span class="line">		dataDictionary.put(<span class="string">&quot;137&quot;</span>,<span class="string">&quot;guangzhou&quot;</span>);</span><br><span class="line">		dataDictionary.put(<span class="string">&quot;138&quot;</span>,<span class="string">&quot;shenzhen&quot;</span>);</span><br><span class="line">		dataDictionary.put(<span class="string">&quot;139&quot;</span>,<span class="string">&quot;shanghai&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">evaluate</span><span class="params">(String phone)</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 如果没有匹配到对应的区域则返回&quot;other&quot;</span></span><br><span class="line">		<span class="keyword">return</span> areaMap.get(phone.substring(<span class="number">0</span>, <span class="number">3</span>)) == <span class="keyword">null</span> ? <span class="string">&quot;other&quot;</span> : areaMap</span><br><span class="line">				.get(phone.substring(<span class="number">0</span>, <span class="number">3</span>));</span><br><span class="line"></span><br><span class="line">	&#125;	</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="添加jar包到Hive"><a href="#添加jar包到Hive" class="headerlink" title="添加jar包到Hive"></a>添加jar包到Hive</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">方式1:添加到hive</span><br><span class="line">hive&gt; add jar &#x2F;root&#x2F;MyUDF.jar;</span><br><span class="line"></span><br><span class="line">方式2:添加到hdfs,调用时需要指定jar包地址</span><br><span class="line">hdfs -dfs -put MyUDF.jar &#39;hdfs:&#x2F;&#x2F;&#x2F;user&#x2F;hadoop&#x2F;hiveUDF&#39;</span><br></pre></td></tr></table></figure>
<h4 id="创建临时函数"><a href="#创建临时函数" class="headerlink" title="创建临时函数"></a>创建临时函数</h4><p>&nbsp;&nbsp;临时函数只在当前session中有效,临时函数不能指定库。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">create temporary function testUDF as &#39;cn.sylvanas.hive.udf.FindRegionByPhone&#39; using jar &#39;hdfs:&#x2F;&#x2F;&#x2F;user&#x2F;hadoop&#x2F;hiveUDF&#x2F;MyUDF.jar&#39;</span><br></pre></td></tr></table></figure>
<h4 id="创建永久函数"><a href="#创建永久函数" class="headerlink" title="创建永久函数"></a>创建永久函数</h4><p><strong>格式</strong></p>
<p>CREATE FUNCTION [db_name.]function_name AS class_name[USING JAR|FILE|ARCHIVE ‘file_uri’ [, JAR|FILE|ARCHIVE ‘file_uri’] ];</p>
<p><strong>例如</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">create function test.testUDF as &#39;cn.sylvanas.hive.udf.FindRegionByPhone&#39; using jar &#39;hdfs:&#x2F;&#x2F;&#x2F;user&#x2F;hadoop&#x2F;hiveUDF&#x2F;MyUDF.jar&#39;</span><br><span class="line"></span><br><span class="line">函数需要属于某个库,如这里是’test’,当其他库调用时,需要加上库名,如’test.testUDF’.</span><br><span class="line"></span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/Hadoop/" rel="tag"># Hadoop</a>
              <a href="/yuwanzi.io/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" rel="tag"># 大数据</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/07/17/2016-07-17-Hadoop04-HBase/" rel="prev" title="Hadoop学习笔记(4)-HBase">
                  <i class="fa fa-chevron-left"></i> Hadoop学习笔记(4)-HBase
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/07/19/2016-07-19-Hadoop06-Storm/" rel="next" title="Hadoop学习笔记(6)-Storm">
                  Hadoop学习笔记(6)-Storm <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
